<template>
  <effect-scatter-map :class="className" :width="width" :height="height" :chart-data="chartData" :center="center" :zoom="5" :title="title" :tooltip-formatter="tooltipFormatter" />
</template>

<script>
import EffectScatterMap from '@/components/EffectScatterMap'
import { listOrgUnit } from '@/api/org-units'
import { getOrgUnitTooltipData } from '@/api/dashboard'

export default {
  components: {
    EffectScatterMap
  },
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '640px'
    }
  },
  data() {
    return {
      title: '加盟商/店铺分布图',
      timeout: null,
      chartData: [],
      center: [104.114129, 37.550339]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.loadData()
    })
  },

  destroyed() {
    if (this.timeout) {
      clearTimeout(this.timeout)
      this.timeout = null
    }
  },
  methods: {
    loadData() {
      const limit = 50
      listOrgUnit({ page: 1, limit: limit }).then(({ success, data }) => {
        if (success) {
          const { pages, current, records } = data || {}
          const arr = []
          if (records && records.length > 0) {
            for (let i = 0; i < records.length; ++i) {
              const item = this.convertAddress(records[i])
              if (item) {
                arr.push(item)
              }
            }
          }
          let page = parseInt(current)
          const totalPage = parseInt(pages)
          while (page < totalPage) {
            this.loadPageData(current + 1, limit, arr)
            page++
          }
          this.chartData = arr
        } else {
          this.timeout = setTimeout(this.loadData, 2 * 1000) // 2秒后重试
        }
      })
    },
    loadPageData(page, limit, arr) {
      listOrgUnit({ page: page, limit: limit }).then(({ success, data }) => {
        if (success) {
          const { records } = data || {}
          if (records && records.length > 0) {
            for (let i = 0; i < records.length; ++i) {
              const item = this.convertAddress(records[i])
              if (item) {
                arr.push(item)
              }
            }
          }
        }
      })
    },
    convertAddress(orgUnit) {
      if (orgUnit.address && orgUnit.address.lng && orgUnit.address.lat) {
        return {
          name: orgUnit.name,
          value: [orgUnit.address.lng, orgUnit.address.lat, orgUnit.id]
        }
      }
      return null
    },
    tooltipFormatter(params, ticket, callback) {
      getOrgUnitTooltipData(params.value[2]).then(([shopCount, userCount, deviceCount]) => {
        callback(ticket, params.name + '<br/>店铺数:' + shopCount.data + '<br/>用户数:' + userCount.data + '<br/>设备数:' + deviceCount.data)
      })
      return 'Loading'
    }
  }
}
</script>
